import redis from 'redis';

// 创建 Redis 客户端
const client = redis.createClient();

// 监听连接成功事件
client.on('connect', () => {
    console.log('Redis connected successfully!');
});

// 监听连接错误事件
client.on('error', (err) => {
    console.error('Redis connection error:', err);
});

// 确保在连接成功后再执行命令
const ensureConnected = () => {
    return new Promise((resolve, reject) => {
        if (client.connected) {
            resolve();
        } else {
            client.once('connect', resolve);
            client.once('error', reject);
        }
    });
};

export const setToken = async (newToken) => {
    await ensureConnected();
    client.set('auth_token', newToken, (err, reply) => {
        if (err) {
            console.error('Error setting token in Redis:', err);
        } else {
            console.log('Token set in Redis:', reply);
        }
    });
};

export const getToken = async () => {
    await ensureConnected();
    return new Promise((resolve, reject) => {
        client.get('auth_token', (err, token) => {
            if (err) {
                console.error('Error getting token from Redis:', err);
                reject(err);
            } else {
                resolve(token);
            }
        });
    });
};
